<?php
namespace app\index\controller;

use app\index\common\Homebase;

use service\FeishuService;
use service\GuardService;
use service\LadderService;
use think\Cache;
use think\Db;
use think\Exception;

class Index extends Homebase
{

    public function index(){
        //$uid = "15810217293";
        //$timestamp = "1532934542416";
        //$securityKey = "Qazxsw4321";
        //echo base64_encode(md5($uid.$timestamp.$securityKey));exit;
        //dump(GuardService::instance()->Getacclevellists());exit;
        $ladderqrcodeinfo = LadderService::instance()->getqrcode(FeishuService::instance()->GetUserfloorinfo(self::$homeuser_info['user_id']));
        //dump($ladderqrcodeinfo);exit;
        //获取门禁二维码信息
        $guardqrcodeinfo = GuardService::instance()->getqrcode(self::$homeuser_info['user_id']);
        //dump($guardqrcodeinfo);exit;
        $unifyqrcode = $ladderqrcodeinfo['enceypted'].LadderService::LGSPLIT.$guardqrcodeinfo;
        //dump($unifyqrcode);exit;
        $this->assign("unifyqrcode",$unifyqrcode);
        $this->assign("ladderqrcodeinfo",$ladderqrcodeinfo);
        return $this->fetch();
    }

    public function getqrcodeinfo(){
        $ladderqrcodeinfo = LadderService::instance()->getqrcode(FeishuService::instance()->GetUserfloorinfo(self::$homeuser_info['user_id']));
        //dump($ladderqrcodeinfo);exit;
        //获取门禁二维码信息
        $guardqrcodeinfo = GuardService::instance()->getqrcode(self::$homeuser_info['user_id']);
        //dump($guardqrcodeinfo);exit;
        $unifyqrcode = $ladderqrcodeinfo['enceypted'].LadderService::LGSPLIT.$guardqrcodeinfo;
        $data = ['unifyqrcode'=>$unifyqrcode,'hex_data'=>$ladderqrcodeinfo['hex_data']];
        $this->success('ok', null, $data);
    }

    public function visitor(){
        $state = $this->request->get("state", 1, "intval");
        $type = $this->request->get('type', 0, 'intval');
        $this->assign("state", $state);
        $where = [];
        $wherestr = "";
        $ctime = time();
        if ($state == 1) {
            $where['visitoretime'] = ['>=', $ctime];
            $where['state'] = 1;
        } elseif ($state == 2) {
            $wherestr = "visitoretime < {$ctime} or state = 2";
        }
        $where['user_id|create_byid'] = self::$homeuser_info['user_id'];
        $lists = Db::name('visitor')
            ->where($where)
            ->where($wherestr)
            ->order("id desc")
            ->paginate(3, false, ['type' => 'BootstrapDetailed', 'query' => $this->request->request()])->toArray();
        //echo Db::name('visitor')->getLastSql();exit;
        //dump($lists);exit;
        if($type == 1){
            foreach ($lists['data'] as &$row){
                $row['visitorstime'] = date("Y-m-d H:i",$row['visitorstime']);
            }
            return json($lists);
        }
        $this->assign("lists",$lists);
        return $this->fetch();
    }

    public function cancelvisitor(){
        $id = $this->request->post("id");
        $visitorinfo = Db::name("visitor")->where(['id'=>$id])->find();
        if(empty($visitorinfo)){
            $this->error("非法操作！");
        }
        if(!empty($visitorinfo) && ($visitorinfo['create_byid'] != self::$homeuser_info['user_id'])){
            $this->error("请提交人操作提交操作！");
        }
        try {
            Db::name("visitor")->where(['id'=>$id])->update(['state'=>2]);
            $this->AddsgLogs("取消邀约记录");
        }
        catch (Exception $exception){
            $this->error($exception->getMessage());
        }
        $this->success("取消邀约成功！");
    }

    public function addvisitor(){
        if ($this->request->isAjax()) {
            $data = $this->request->post();
            if(empty($data['visitoruname'])){
                $this->error("请输入访客姓名");
            }
            if(empty($data['visitorphone'])){
                $this->error("请输入访客手机号码");
            }
            if(empty($data['visitornum'])){
                $this->error("请输入来访人数");
            }
            //拜访开始时间
            if(empty($data['visitorsdate'])){
                $this->error("请输入拜访开始日期");
            }
            if(empty($data['visitorstime'])){
                $this->error("请输入拜访开始时间");
            }
            $data['visitorstime'] = strtotime($data['visitorsdate']." ".$data['visitorstime']);
            unset($data['visitorsdate']);
            if(empty($data['visitoredate'])){
                $this->error("请输入拜访结束日期");
            }
            if(empty($data['visitoretime'])){
                $this->error("请输入拜访结束时间");
            }
            $data['visitoretime'] = strtotime($data['visitoredate']." ".$data['visitoretime']);
            unset($data['visitoredate']);
            if($data['visitoretime'] < $data['visitorstime']){
                $this->error("拜访结束时间不能小于拜访开始时间");
            }
            if(empty($data['visitorbuilderinfo'])){
                $this->error("请输入楼栋信息，例如：X座X楼");
            }
            if(empty($data['visitor_reason'])){
                $this->error("请输入来访事由");
            }
            //访客码
            $data['visitorkey'] = randSole(6,8);
            //给访客发送短信
            $visitorstime = date("Y-m-d H:i",$data['visitorstime']);
            $uname = self::$homeuser_info['username'];
            $uphone = self::$homeuser_info['mobile'];
            $data['msg_content'] = "尊敬的来宾，您已预约{$visitorstime}到访绿城中国，地址：浙江省杭州市西湖区杭大路1号黄龙世纪广场{$data['visitorbuilderinfo']}。请保存此短信，届时凭二维码https://elevatorc.gtcloud.cn/xcx/{$data['visitorkey']}入园，接洽姓名{$uname}，联系电话：{$uphone}。";
            $msg_res = sendmsg($data['visitorphone'],$data['msg_content']);
            if($msg_res['errorcode'] != 1){
                $this->error($msg_res['message']);
            }
            $data['sendmsg_res'] = json_encode($msg_res,304);
            $data['create_time'] = time();
            $data['user_id'] = $data['create_byid'] = self::$homeuser_info['user_id'];
            //dump($data);exit;
            try {
                $res_id = db("visitor")->insertGetId($data);
                if($res_id){
                    Cache::store('redis')->set($data['visitorkey'], $res_id);
                }
                $this->AddsgLogs("新增邀约记录");
            }
            catch (Exception $exception){
                $this->error($exception->getMessage());
            }
            $this->success("登记成功！");
        }
        return $this->fetch();
    }

}
